package com.szh.gulimall.order.listener;

import com.rabbitmq.client.Channel;
import com.szh.gulimall.order.entity.OrderEntity;
import com.szh.gulimall.order.service.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @author: SongZiHao
 * @date: 2023/2/6
 */
@Service
public class OrderCloseListener {

    private static final Logger LOGGER = LoggerFactory.getLogger(OrderCloseListener.class);

    @Autowired
    private OrderService orderService;

    @RabbitHandler
    @RabbitListener(queues = "order.release.order.queue")
    public void listener(OrderEntity orderEntity, Message message, Channel channel) throws IOException {
        LOGGER.info("收到过期未付款的订单，准备关闭订单号为 {} 的订单....", orderEntity.getOrderSn());
        try {
            //关闭订单
            orderService.closeOrder(orderEntity);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException ex) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }
}
